﻿using System;
using System.IO;
using Innoapps.FileTransfer.Models;
using System.Xml.Serialization;

namespace Innoapps.FileTransfer.Providers.Cache
{
    public class FileSystem : Base
    {

        #region Properties
        [XmlAttribute("FolderPath")]
        public string FolderPath { get; set; }
        #endregion

        #region Methods
        public override void Load(Transfer transfer)
        {

            try
            {
                FileStream stream = new FileStream(Path.Combine(FolderPath, transfer.Id + ".tmp"), FileMode.Open);
                transfer.Stream = stream;
            } catch(Exception e)
            {
                transfer.Stream = null;
                throw e;
            }

            
        }

        public override void Save(Transfer transfer)
        {
            try
            {
                FileStream stream = new FileStream(Path.Combine(FolderPath, transfer.Id + ".tmp"), FileMode.Create);
                transfer.Stream.CopyTo(stream);
                stream.Flush();
                stream.Close();
                transfer.Stream = null;
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        public override void Destroy(Transfer transfer)
        {
            try
            {
                if (transfer.Stream != null)
                    transfer.Stream.Close();
                System.IO.File.Delete(Path.Combine(FolderPath, transfer.Id + ".tmp"));
                transfer.Stream = null;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        #endregion
    }
}
